import { createRef, RefObject } from 'react'
import { create } from 'zustand'
import _ from 'lodash'
import { message } from 'antd'

import { AgGridReact } from '@/components/CusAgGrid'
import { apiBatchAddOrigRoute } from '../apis'
import { IBatchAddOrigRouteItem } from './interface'
import { createEmptyRows, getRowData, ROW_NUM } from './utils'

export interface IStore {
  gridRef: RefObject<AgGridReact<IBatchAddOrigRouteItem>>
  /** 注意：编辑时是直接修改源数据的 */
  data: IBatchAddOrigRouteItem[]
  isValid: boolean
  submitting: boolean
  hasSucceeded: boolean
  currentCountInfo: null | {
    totalNum: number
    successNum: number
    failNum: number
  }
  /** 注意：这个方法会清空撤销历史，慎用受控 */
  setData: (data: IBatchAddOrigRouteItem[]) => void
  validate: () => void
  handleSubmit: () => void
}

export const useBoundStore = create<IStore>((set, get) => {
  return {
    gridRef: createRef(),
    data: [],
    isValid: false,
    submitting: false,
    hasSucceeded: false,
    currentCountInfo: null,
    setData: data => set({ data }),
    validate: () => {
      const { gridRef, isValid } = get()
      const { noEmptyRowData, validRowData } = getRowData(gridRef)
      const valid = noEmptyRowData.length ? noEmptyRowData.length === validRowData.length : false
      if (isValid !== valid) {
        set({ isValid: valid })
      }
    },
    handleSubmit: () => {
      const { gridRef, hasSucceeded } = get()
      const { rowData, validRowData, validRowIndexs } = getRowData(gridRef)
      if (validRowData.length > 0) {
        const send = async () => {
          try {
            set({ submitting: true })
            const { routeResList, totalNum, successNum, failNum } = await apiBatchAddOrigRoute(
              validRowData.map(d => _.pick(d, ['waybillNo', 'originalRoute', 'occurDate'])),
            )
            const deleteIndexs: number[] = []
            routeResList.forEach((d, i) => {
              if (d.resultType === 1) {
                deleteIndexs.push(validRowIndexs[i])
                return
              }
              rowData[validRowIndexs[i]].resultType = d.resultType
              rowData[validRowIndexs[i]].resultDesc = d.resultDesc
              rowData[validRowIndexs[i]].merchantServers = d.merchantServers
              rowData[validRowIndexs[i]].channelNo = d.channelNo
            })
            let data = rowData
            data = data.filter((d, i) => !deleteIndexs.includes(i) && (d.waybillNo || d.originalRoute || d.occurDate)) // 移除成功的 & 移除空行
            data = data.concat(...createEmptyRows(ROW_NUM - data.length)) // 追加空行
            set({
              data: data, // 同时也会清空撤销历史
              hasSucceeded: hasSucceeded ? true : successNum > 0,
              currentCountInfo: { totalNum, successNum, failNum },
            })
            if (failNum) message.warning(`本次导入，成功${successNum}条，失败${failNum}条`)
            else message.success(`本次导入，成功${successNum}条`)
            gridRef.current?.api?.ensureIndexVisible(0, 'top')
          } finally {
            set({ submitting: false })
          }
        }
        send()
      }
    },
  }
})
